package RTDGDiscovery;

import host.IHost;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import org.apache.log4j.Priority;

import properties.PropertyManager;

import manager.ServiceManager;

public class DiscoveryDispatcher{
	private IHost hostGroup;
	private InetAddress groupAddress;
	private InetAddress thisIp;
	private MulticastSocket sendingSocket;
	private int byteArraySize;
	
	public IHost getHostGroup() {
		return hostGroup;
	}

	public void setHostGroup(IHost hostGroup) {
		this.hostGroup = hostGroup;
	}

	public int getByteArraySize() {
		return byteArraySize;
	}

	public void setByteArraySize(int byteArraySize) {
		this.byteArraySize = byteArraySize;
	}

	public DiscoveryDispatcher() {
	}
	
	public void initDiscovery(){
		ServiceManager.printLog(Priority.INFO_INT,PropertyManager.properties.getProperty("dispatcherInitialisation"));
		try {
			thisIp = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			ServiceManager.printLog(Priority.ERROR_INT, PropertyManager.properties.getProperty("dispatcherInitialisationError"));
			e.printStackTrace();
		}
		if(groupAddress == null){
			try {
				groupAddress = InetAddress.getByName(hostGroup.getIpAddress());
			} catch (UnknownHostException e) {
				ServiceManager.printLog(Priority.ERROR_INT, PropertyManager.properties.getProperty("groupAddressCreationError"));
				e.printStackTrace();
			}
		}
		try {
			sendingSocket = new MulticastSocket();
		} catch (IOException e) {
			ServiceManager.printLog(Priority.ERROR_INT, PropertyManager.properties.getProperty("dispatcherMulticastSocketCreationError"));
			e.printStackTrace();
		}
	}
	
	public void discover() throws IOException{
		ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("dispacherSend"));
		DatagramPacket packet;
		byte[] byteArray = new byte[byteArraySize];
		String message = thisIp.getHostAddress();
		message = new Integer(ServiceManager.thisHost.getPortNumber()).toString();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		(new DataOutputStream(out)).writeUTF(message);

		byteArray = out.toByteArray();
		
		packet = new DatagramPacket(byteArray, byteArray.length, groupAddress, hostGroup.getPortNumber());
		sendingSocket.send(packet);
		ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("dispacherSendSuccess"));
	}
}
